<template>
  <div>
    <el-descriptions>
      <el-descriptions-item width="50%" label="家庭名称">{{ isNullOrEmpty( formInline.familyName ) }}</el-descriptions-item>
      <el-descriptions-item width="50%" label="所属个体用户">{{ isNullOrEmpty( formInline.userName ) }}</el-descriptions-item>
      < </el-descriptions>
        <div>
          <el-button v-auth="'system.family-unity.create'" type="primary" :icon="Plus" @click="add">授权监管单位</el-button>

        </div>
        <pure-table class="mt-5" :data="tableData.data" :columns="initPureTableConfig(roleTableConfig)" showOverflowTooltip border
          :isShowPag="false">
          <template #deviceIds="{ row }">
              <div v-for="(item,index) in row.devices">
                <!-- {{ isNullOrEmpty( item ) }} -->
                {{ isNullOrEmpty( item.deviceName ) }}
              </div>
          </template>
          <template #action="{ row }">
            <el-space>

              <sj-link custom-type="sblue" :underline="false" @click="edit(row)" v-auth="'system.family-unity.update'">编辑</sj-link>

              <sj-link custom-type="sred" :underline="false" @click="deletes(row)" v-auth="'system.family-unity.delete'">删除</sj-link>
            </el-space>
          </template>
        </pure-table>
        <div class="mt-5">
          <el-pagination v-model:current-page="searchFrom.page" v-model:page-size="searchFrom.limit" background
            :layout="PAGE_LAYOUT" :total="tableData.total" @size-change="getTableList" @current-change="getTableList" />
        </div>
  </div>
</template>
<script lang="ts" setup>
import {isNullOrEmpty,initPureTableConfig} from '@/utils/functions'
import { PAGE_LAYOUT } from '@/constant';
import { Plus, Delete } from '@element-plus/icons-vue';
import { reactive, ref, h } from 'vue';
import { addDialog } from "@/components/ReDialog";
import forms from "../components/form.vue";
import { cloneDeep, isAllEmpty, deviceDetection, debounce } from "@pureadmin/utils";
import { titles, defaultSearchForm, prompt, defaultInfoForm } from './index';
import { getList, getInfo, addInfo, editInfo, deleteInfo } from '@/api/manage/Individual-management/Individual-management/empower'
import type { infoType } from '@/api/manage/Individual-management/Individual-management/empower';
import { message } from "@/utils/message";
import { customDebounce, customPromiseDebounce } from "@/utils/functions";
import { ElMessage, ElMessageBox } from "element-plus";
type FormProps = {
  formInline: infoType,
  isLoading: boolean
}
const showInfo = ref();
const formRef = ref();
const props = withDefaults(defineProps<FormProps>(), {
  formInline: () => ({} as infoType),
  isLoading: false
});
const searchFrom = ref(defaultSearchForm());
 console.log("家庭监管授权", props);

const tableData = reactive({
  data: [],
  total: 0,

});
const roleTableConfig = [
  // { type: "selection", align: "left" },

   { prop: 'id', label: titles.id, width:  100,  fixed: 'left' },
  { prop: 'unityName', label: titles.unityName },
  // { prop: 'familyName', label: titles.familyName },
  { slot: 'deviceIds', label: titles.deviceIds,},
  { prop: 'operatorName', label: titles.operatorName },
  { prop: 'updatedAt', label: titles.updatedAt },
  { slot: 'action', label: titles.action, width: 150, fixed: 'right' },
];
onMounted(() => {
  setTimeout(()=>{
    getTableList()
  },500)
 
});
// 获取列表数据
const getTableList = () => {
  searchFrom.value.familyId = props.formInline?.id
  console.log('打印列表',searchFrom.value.familyId);
  
  getList(searchFrom.value).then(res => {
    if (res.code === 200) {
      tableData.data = res.result.data;
      tableData.total = res.result.total;
    }
  })
}

// 新增
const add = (row) => {
  showInfo.value = {}
  openDialog()
}
// 编辑
const edit = (row) => {
  showInfo.value = {}
  openDialog("编辑家庭监管单位", row)
}
const openDialog = (title = "添加家庭监管单位", row?: any) => {
  addDialog({
    title: `${title}`,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(forms, { ref: formRef }),
    openAutoFocus({ options, index }) {
      if (row) {
        options.props = {
          isLoading: true,
          formInline: defaultInfoForm(),
          familyName: props.formInline
        }
        getInfo({ id: row.id }).then(res => {
          if (res.code == 200) {
            showInfo.value = res.result.data
            options.props.formInline = res.result.data
          }
        }).finally(() => {
          options.props.isLoading = false
          
        })
      } else {
        options.props = {
          isLoading: false,
          formInline: defaultInfoForm(),
          familyName: props.formInline
        }
      }
    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      const formData = options.props.formInline;
      formData.userId =props.formInline.userId
      formData.familyId =props.formInline.id,
       console.log('formData',formData);
      
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        getTableList(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          // console.log("formData", formData);
          // 表单规则校验通过
          options.props.isLoading = true;
          if (title === "添加家庭监管单位") {
            DebounceAddInfo(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          } else {
            DebounceEditInfo(formData).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          }
        }
      });
    }
  });
}

// 删除
const deletes = (row?) => {
  ElMessageBox.confirm(
    `确认删除${row ? '当前' : '选中的'}数据?`,
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      deleteInfo({ ids:[row.id]  }).then(res => {
        if (res.code == 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          getTableList();
        }
      })
    })
}
const DebounceAddInfo = customPromiseDebounce(addInfo, 1000, true);
// 编辑请求
const DebounceEditInfo = customPromiseDebounce(editInfo, 1000, true);
</script>